# -*- coding: utf-8 -*-
# standard
import os
import sys
import re
from datetime import datetime
from enum import Enum
from typing import Dict
from typing import List
from typing import Optional
from collections import Counter

# third
import matplotlib.pyplot as plt  # pip install matplotlib


# local
_P_PATH =  os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
if _P_PATH not in sys.path:
    sys.path.append(_P_PATH)
from models import *


"""
@Title:   
@File: 绘制上传的图.py
@Author: walle 2023年07日05日 18时29分26秒
@Version: 1.0.0
@Desc: 
"""




BEGIN = datetime(2023, 12, 13, 0, 0, 0)
BEGIN = datetime(2023, 12, 19, 16, 0, 0)  # 增加至7线程
BEGIN = datetime(2023, 12, 27, 10, 0, 0)  


def draw_download_h1():
    """
    画出上传数量直方图
    :param n: 直方图的区间
    :return:
    """
    begin = BEGIN
    db_session = new_db_session()
    # query = db_session.query(RawVideoObjectOrm.download_time).filter(and_(RawVideoObjectOrm.download_time != None, RawVideoObjectOrm != 1)).order_by(RawVideoObjectOrm.download_time.asc()).first()
    cond = and_(PutRecordOrm.copy_begin != None, 
                PutRecordOrm.copy_end != None,
                PutRecordOrm.copy_end >= begin,
                PutRecordOrm.is_copied == 1)
    query = db_session.query(PutRecordOrm).where(cond)
    data1 = {}  # 小时和下载文件数组成的字典
    for x in query:
        key = x.copy_end.strftime('%m-%d %H')
        key = int((x.copy_end - begin).total_seconds() / 3600)
        value1 = data1.get(key, 0)
        value1 += 1
        data1[key] = value1
    data1 = [{"time": k, "counter": v} for k, v in data1.items()]
    data1.sort(key=lambda x: x['time'])
    x1, y1 = [], []
    for item in data1:
        x1.append(item['time'])
        y1.append(item['counter'])
    db_session.close()
    fig = plt.figure(figsize=(16, 8))  # 设置大小
    plt.xticks(rotation=True) 
    plt.title("每小时上传视频个数(个/小时)", fontdict={"family": "SimSun"})
    plt.xlabel("时间", fontdict={"family": "SimSun"})
    plt.ylabel("上传个数", fontdict={"family": "SimSun"})  
    # ax1.plot(x, y)
    plt.bar(x1, y1)
    fig.savefig(os.path.join(R_P_PATH, "test", "上传速度（个数）直方图.png"))
    # plt.show()
    # plt.pause(999)


def draw_download_h2():
    """
    画出下载流量直方图
    :param n: 直方图的区间
    :return:
    """
    begin = BEGIN
    db_session = new_db_session()
    # query = db_session.query(RawVideoObjectOrm.download_time).filter(and_(RawVideoObjectOrm.download_time != None, RawVideoObjectOrm != 1)).order_by(RawVideoObjectOrm.download_time.asc()).first()
    cond = and_(PutRecordOrm.copy_begin != None, 
                PutRecordOrm.copy_end != None,
                PutRecordOrm.copy_end >= begin,
                PutRecordOrm.is_copied == 1)
    query = db_session.query(PutRecordOrm).where(cond)
    data2 = {} # 小时和下载文件大小组成的字典
    for x in query:
        # key = x.copy_end.strftime('%m-%d %H')
        key = int((x.copy_end - begin).total_seconds() / 3600)
        value2 = data2.get(key, 0)
        value2 += x.file_size # 单位 字节
        data2[key] = value2
    data2 = [{"time": k, "size": v} for k, v in data2.items()]
    data2.sort(key=lambda x: x['time'])
    x2, y2 = [], []
    for item in data2:
        x2.append(item['time'])
        y2.append(item['size'] / (1024 ** 3))  # 单位 G
    db_session.close()
    fig = plt.figure(figsize=(16, 8))  # 设置大小
    plt.xticks(rotation=True) 
    plt.title("每小时上传视频流量(G/小时)", fontdict={"family": "SimSun"})
    plt.xlabel("时间", fontdict={"family": "SimSun"})
    plt.ylabel("上传流量", fontdict={"family": "SimSun"})  
    # ax1.plot(x, y)
    plt.bar(x2, y2)
    fig.savefig(os.path.join(R_P_PATH, "test", "上传速度（尺寸）直方图.png"))
    # plt.show()
    # plt.pause(999)




if __name__ == '__main__':
    draw_download_h1()
    draw_download_h2()
    pass